package com.wwg.warehouse.utils;

import android.util.Log;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class EncryptUtil {
    private static final String TAG = "EncryptUtil";

    public static String sha256Encrypt(String encryptMsg) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(encryptMsg.getBytes(StandardCharsets.UTF_8));
            result = bytes2Hex(messageDigest.digest());
        } catch (Exception e) {
            Log.e(TAG, "shaEncrypt error = " + e);
        }
        return result;
    }

    public static String sha1Encrypt(String encryptMsg) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(encryptMsg.getBytes(StandardCharsets.UTF_8));
            result = bytes2Hex(messageDigest.digest());
        } catch (Exception e) {
            Log.e(TAG, "shaEncrypt error = " + e);
        }
        return result;
    }

    public static String md5Encrypt(String encryptMsg) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(encryptMsg.getBytes(StandardCharsets.UTF_8));
            result = bytes2Hex(messageDigest.digest());
        } catch (Exception e) {
            Log.e(TAG, "shaEncrypt error = " + e);
        }
        return result;
    }

    private static String bytes2Hex(byte[] bts) {
        if ((bts == null) || (bts.length == 0)) {
            Log.e(TAG, "bytes2Hex bts is empty");
            return null;
        }
        StringBuilder des = new StringBuilder();
        String tmp = "";
        for (byte bt : bts) {
            tmp = Integer.toHexString(bt & 0xFF);
            if (tmp.length() == 1) {
                des.append("0");
            }
            des.append(tmp);
        }
        return des.toString();
    }
}
